const express = require("express");
const md5 = require("blueimp-md5");
const router = express.Router();
const UserModel = require("../models/UserModel");
const RoleModel = require("../models/RoleModel");
const SchoolModel = require("../models/SchoolModel");
const majorsModel = require("../models/MajorsModel");
const ClassModel = require("../models/ClassModel");
const StudentModel = require("../models/StudentModel");

router.get("/test", (req, res) => {
  res.send("测试成功");
});
//登录
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne({ username, password: md5(password) })
    .then((user) => {
      if (user) {
        if (user.role_id) {
          RoleModel.findOne({ _id: user.role_id }).then((role) => {
            user._doc.role = role;
            console.log("role user", user);
            res.send({ status: 0, data: user });
          });
        } else {
          user._doc.role = { menus: [] };
          res.send({ status: 0, data: user });
        }
      } else {
        res.send({ status: 1, msg: "用户名或密码不正确" });
      }
    })
    .catch((err) => {
      console.log(err);
      res.send({ status: 1, msg: "服务异常 请稍后再试" });
    });
});
//获取角色
router.get("/manage/role/list", (req, res) => {
  RoleModel.find()
    .then((roles) => {
      res.send({ status: 0, data: roles });
    })
    .catch((err) => {
      console.log("获取角色列表失败", err);
      res.send({ status: 1, msg: "获取角色列表失败，请稍后再试" });
    });
});
//添加角色
router.post("/manage/role/add", (req, res) => {
  const { name } = req.body;
  RoleModel.create({ name })
    .then((role) => {
      res.send({ status: 0, data: role });
    })
    .catch((err) => {
      console.log("添加角色列表失败", err);
      res.send({ status: 1, msg: "添加角色失败，请稍后再试" });
    });
});
//更新角色
router.post("/manage/role/update", (req, res) => {
  const role = req.body;
  role.auth_time = Date.now();
  RoleModel.findOneAndUpdate({ _id: role._id }, role)
    .then((Oldrole) => {
      res.send({ status: 0, data: { ...Oldrole._doc, ...role } });
    })
    .catch((err) => {
      console.log("添加角色列表失败", err);
      res.send({ status: 1, msg: "添加角色失败，请稍后再试" });
    });
});
//获取用户
router.get("/manage/user/all", (req, res) => {
  UserModel.find({ username: { $ne: "admin" } })
    .then((users) => {
      res.send({ status: 0, data: users });
    })
    .catch((err) => {
      console.log("获取用户列表失败", err);
      res.send({ status: 1, msg: "获取用户列表失败，请稍后再试" });
    });
});
//获取分页用户列表
router.post("/manage/user/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  UserModel.find({ username: { $ne: "admin" } })
    .then((users) => {
      let count = users.length;
      UserModel.find({ username: { $ne: "admin" } })
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          RoleModel.find().then((roles) => {
            res.send({ status: 0, data: { total: count, data, roles } });
          });
        });
    })
    .catch((err) => {
      console.log("获取用户列表失败", err);
      res.send({ status: 1, msg: "获取用户列表失败，请稍后再试" });
    });
});
//添加用户
router.post("/manage/user/add", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne({ username })
    .then((user) => {
      if (user) {
        res.send({ status: 1, msg: "当前账户已存在" });
        return new Promise(() => {});
      } else {
        return UserModel.create({ ...req.body, password: md5(password) });
      }
    })
    .then((user) => {
      res.send({ status: 0, data: user });
    })
    .catch((err) => {
      console.log("注册失败", err);
      res.send({ status: 1, msg: "添加用户失败，请稍后再试" });
    });
});
//根据id查询用户
router.get("/manage/user/find", (req, res) => {
  const user = req.query;
  UserModel.findById({ _id: user._id })
    .then((data) => {
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("ID查询用户失败", err);
      res.send({ status: 1, msg: "查询用户失败，请稍后再试" });
    });
});
//更新用户
router.post("/manage/user/update", (req, res) => {
  const user = req.body;
  UserModel.findOne({_id:user._id}).then(data=>{
    if(data.password != user.password){
      user.password = md5(user.password)
    }
    UserModel.findOneAndUpdate({ _id: user._id }, user)
    .then((olduser) => {
      const data = Object.assign(olduser, user);
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("更新用户失败", err);
      res.send({ status: 1, msg: "更新用户失败，请稍后再试" });
    });
  })
});
//删除用户
router.post("/manage/user/delete", (req, res) => {
  const { userId } = req.body;
  UserModel.deleteOne({ _id: userId }).then((doc) => {
    res.send({ status: 0 });
  });
});
//获取权限列表
router.post("/menus", (req, res) => {
  console.log("roleId", req.body);
  const { roleId } = req.body;
  RoleModel.findOne({ _id: roleId })
    .then((role) => {
      console.log("role", role);
      res.send({ status: 0, data: { menus: role.menus } });
    })
    .catch((err) => {
      console.log("获取权限列表失败", err);
      res.send({ status: 1, msg: "获取权限列表失败，请稍后再试" });
    });
});
//获取学校
router.get("/manage/school/all", (req, res) => {
  SchoolModel.find()
    .then((list) => {
      res.send({ status: 0, data: list });
    })
    .catch((err) => {
      console.log("获取学校列表失败", err);
      res.send({ status: 1, msg: "获取班级学校失败，请稍后再试" });
    });
});
//获取学校列表
router.post("/manage/school/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  SchoolModel.find({})
    .then((schools) => {
      let count = schools.length;
      SchoolModel.find()
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((err) => {
      console.log("获取学校列表失败", err);
      res.send({ status: 1, msg: "获取学校列表失败，请稍后再试" });
    });
});
//添加学校
router.post("/manage/school/add", (req, res) => {
  const { schoolname } = req.body;
  SchoolModel.findOne({ schoolname })
    .then((school) => {
      if (school) {
        res.send({ status: 1, msg: "当前学校已存在" });
        return new Promise(() => {});
      } else {
        return SchoolModel.create({ ...req.body });
      }
    })
    .then((school) => {
      res.send({ status: 0, data: school });
    })
    .catch((err) => {
      console.log("添加学校失败", err);
      res.send({ status: 1, msg: "添加学校失败，请稍后再试" });
    });
});
//根据id查询学校
router.get("/manage/school/find", (req, res) => {
  const school = req.query;
  SchoolModel.findById({ _id: school._id })
    .then((data) => {
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("ID查询用户失败", err);
      res.send({ status: 1, msg: "查询用户失败，请稍后再试" });
    });
});
//更新学校
router.post("/manage/school/update", (req, res) => {
  const school = req.body;
  console.log("school", school._id);
  SchoolModel.findOneAndUpdate({ _id: school._id }, school)
    .then((oldSchool) => {
      const data = Object.assign(oldSchool, school);
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("更新学校失败", err);
      res.send({ status: 1, msg: "更新学校失败，请稍后再试" });
    });
});
//删除学校
router.post("/manage/school/delete", (req, res) => {
  const { schoolId } = req.body;
  SchoolModel.deleteOne({ _id: schoolId }).then((doc) => {
    res.send({ status: 0 });
  });
});
//获取专业
router.get("/manage/majors/all", (req, res) => {
  majorsModel.find()
    .then((list) => {
      res.send({ status: 0, data: list });
    })
    .catch((err) => {
      console.log("获取专业列表失败", err);
      res.send({ status: 1, msg: "获取班级专业失败，请稍后再试" });
    });
});
//获取专业列表
router.post("/manage/majors/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  majorsModel
    .find({})
    .then((majorss) => {
      let count = majorss.length;
      majorsModel
        .find()
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((err) => {
      console.log("获取专业列表失败", err);
      res.send({ status: 1, msg: "获取专业列表失败，请稍后再试" });
    });
});
//添加专业
router.post("/manage/majors/add", (req, res) => {
  const { majorsname } = req.body;
  majorsModel
    .findOne({ majorsname })
    .then((majors) => {
      if (majors) {
        res.send({ status: 1, msg: "当前专业已存在" });
        return new Promise(() => {});
      } else {
        return majorsModel.create({ ...req.body });
      }
    })
    .then((majors) => {
      res.send({ status: 0, data: majors });
    })
    .catch((err) => {
      console.log("添加专业失败", err);
      res.send({ status: 1, msg: "添加专业失败，请稍后再试" });
    });
});
//根据id查询专业
router.get("/manage/majors/find", (req, res) => {
  const majors = req.query;
  majorsModel
    .findById({ _id: majors._id })
    .then((data) => {
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("ID查询专业失败", err);
      res.send({ status: 1, msg: "查询专业失败，请稍后再试" });
    });
});
//更新专业
router.post("/manage/majors/update", (req, res) => {
  const majors = req.body;
  console.log("majors", majors._id);
  majorsModel
    .findOneAndUpdate({ _id: majors._id }, majors)
    .then((oldmajors) => {
      const data = Object.assign(oldmajors, majors);
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("更新专业失败", err);
      res.send({ status: 1, msg: "更新专业失败，请稍后再试" });
    });
});
//删除专业
router.post("/manage/majors/delete", (req, res) => {
  const { majorsId } = req.body;
  majorsModel.deleteOne({ _id: majorsId }).then((doc) => {
    res.send({ status: 0 });
  });
});
//获取班级列表
router.get("/manage/class/all", (req, res) => {
  ClassModel.find()
    .then((list) => {
      res.send({ status: 0, data: list });
    })
    .catch((err) => {
      console.log("获取班级列表失败", err);
      res.send({ status: 1, msg: "获取班级列表失败，请稍后再试" });
    });
});
//获取分页班级列表
router.post("/manage/class/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  let searchMap = req.body.searchMap || {};
  let obj = {};
  searchMap.teacher_id ? (obj["teacher_id"] = searchMap.teacher_id) : obj;
  searchMap.manager_id ? (obj["manager_id"] = searchMap.manager_id) : obj;
  ClassModel.find(obj)
    .then((classs) => {
      let count = classs.length;
      ClassModel.find(obj)
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((err) => {
      console.log("获取班级列表失败", err);
      res.send({ status: 1, msg: "获取班级列表失败，请稍后再试" });
    });
});
//添加班级
router.post("/manage/class/add", (req, res) => {
  const { classname } = req.body;
  ClassModel.findOne({ classname })
    .then((classs) => {
      if (classs) {
        res.send({ status: 1, msg: "当前专业已存在" });
        return new Promise(() => {});
      } else {
        return ClassModel.create({ ...req.body });
      }
    })
    .then((classs) => {
      res.send({ status: 0, data: classs });
    })
    .catch((err) => {
      console.log("添加专业失败", err);
      res.send({ status: 1, msg: "添加专业失败，请稍后再试" });
    });
});
//根据id查询班级
router.get("/manage/class/find", (req, res) => {
  const c = req.query;
  ClassModel.findById({ _id: c._id })
    .then((data) => {
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("ID查询班级失败", err);
      res.send({ status: 1, msg: "查询班级失败，请稍后再试" });
    });
});
//更新班级
router.post("/manage/class/update", (req, res) => {
  const c = req.body;
  console.log("class", c._id);
  ClassModel.findOneAndUpdate({ _id: c._id }, c)
    .then((oldclass) => {
      const data = Object.assign(oldclass, c);
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("更新班级失败", err);
      res.send({ status: 1, msg: "更新班级失败，请稍后再试" });
    });
});
//删除班级
router.post("/manage/class/delete", (req, res) => {
  const { classId } = req.body;
  ClassModel.deleteOne({ _id: classId }).then((doc) => {
    res.send({ status: 0 });
  });
});
//获取学员列表
router.post("/manage/student/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  let searchMap = req.body.searchMap || {};
  let obj = {};
  searchMap.name ? (obj["name"] = searchMap.name) : obj;
  searchMap.direction ? (obj["direction"] = searchMap.direction) : obj;
  searchMap.class ? (obj["class"] = searchMap.class) : obj;
  searchMap.teacher_id ? (obj["teacher_id"] = searchMap.teacher_id) : obj;
  searchMap.manager_id ? (obj["manager_id"] = searchMap.manager_id) : obj;
  StudentModel.find(obj)
    .then((students) => {
      let count = students.length;
      StudentModel.find(obj)
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((err) => {
      console.log("获取学员列表失败", err);
      res.send({ status: 1, msg: "获取学员列表失败，请稍后再试" });
    });
});
//添加学员
router.post("/manage/student/add", (req, res) => {
  StudentModel.create({ ...req.body })
    .then((data) => {
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("添加学员失败", err);
      res.send({ status: 1, msg: "添加学员失败，请稍后再试" });
    });
});
//根据id查询学员
router.get("/manage/student/find", (req, res) => {
  const student = req.query;
  StudentModel.findById({ _id: student._id })
    .then((data) => {
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("ID查询学员失败", err);
      res.send({ status: 1, msg: "查询学员失败，请稍后再试" });
    });
});
//更改学员信息
router.post("/manage/student/update", (req, res) => {
  const student = req.body;
  console.log("123",req.body);
  StudentModel.findOneAndUpdate({ _id: student._id }, student)
    .then((oldstudent) => {
      const data = Object.assign(oldstudent, student);
      res.send({ status: 0, data });
    })
    .catch((err) => {
      console.log("更新学员失败", err);
      res.send({ status: 1, msg: "更新学员失败，请稍后再试" });
    });
});
//删除学员
router.post("/manage/student/delete", (req, res) => {
  const { studentId } = req.body;
  StudentModel.deleteOne({ _id: studentId }).then((doc) => {
    res.send({ status: 0 });
  });
});
// 查询某一年学员
router.post('/manage/student/date',(req,res)=>{
  let {year} = req.body
  year=year+""
  StudentModel.aggregate([
     {
    $project:{
      year:{$substr:["$addmission_date",0,4]},
      month:{$substr:["$addmission_date",5,2]},
    }
  },
  {$match:{year}},
  {
    $group:{
      _id:'$month',
      count:{$sum:1}
    }
  },
  {
    $sort:{_id:1}
  }
  ]).exec((err,data)=>{
      if(err){
          console.log('按年份查询异常',err);
          return res.send({status:1,msg:'按年份查询异常,请稍后再试'})
      }

      return res.send({status:0,data})
  })
})
//
router.post('/manage/user/pwd', (req, res) => {
  const body = req.body
  UserModel.findOne({ 
      _id:body._id,
      password:md5(body.password)
   }).then(user => {
      if(!user){
          return res.send({ status: 1, msg:"密码不正确" })
      }
      return res.send({ status: 0, data: user })
  })
})
//修改密码
router.put('/manage/user/pwd',(req,res)=>{
  const _id=req.body.userId
  UserModel.findOne({_id:_id}).then(user=>{
      if(!user){
          res.send({status:1,msg:'用户不存在'})
      }
      user.password = md5(req.body.password)
      UserModel.findByIdAndUpdate(_id,user).then(()=>{
          return res.send({status:0,msg:"修改密码成功"})
      }).catch(error => {
          console.error('修改密码异常', error);
          res.send({ status: 1, msg: '修改密码异常，请重新获取' })
      })
  })
})

require('./file-upload')(router)
module.exports = router;
